package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     *
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult pagination(DishPageQueryDTO pageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        //获取菜品
        Page<Dish> p = dishMapper.page(pageQueryDTO);
        PageResult pageResult = new PageResult(p.getTotal(), p.getResult());
        return pageResult;
    }

    /**
     * 根据id批量删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteById(Long[] ids) {
        //查询状态，如果是起售中的菜品则不删除，
        int count = dishMapper.selectStatus(ids);
        if (count>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //如果菜品关联了套餐，则不能删除
        count = setmealDishMapper.quireDish(ids);
        if (count>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        dishMapper.delete(ids);

        //删除菜品口味表对应的数据
        dishFlavorMapper.delete(ids);

        //清理redis中的缓存数据,删除的可能是不同分类下的菜品，直接将redis中的缓存全部删除
        clearRedis("dish_*");
    }

    /**
     * 添加菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void addDishWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        //克隆对象
        BeanUtils.copyProperties(dishDTO, dish);

        //已使用aop自动填充
        //设置创建时间和更新时间，以及操作人
        //dish.setCreateTime(LocalDateTime.now());
        //dish.setCreateUser(BaseContext.getCurrentId());
        //dish.setUpdateTime(LocalDateTime.now());
        //dish.setUpdateUser(BaseContext.getCurrentId());

        dishMapper.addDish(dish);

        //添加口味表dish_flavor数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
            dishFlavorMapper.insert(flavors);
        }

        //清理redis中的缓存数据
        String key = "dish_"+dish.getCategoryId();
        clearRedis(key);
    }

    /**
     * 停售或起售
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(int status, long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);

        //删除redis中对应的缓存
        clearRedis("dish_*");
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        //克隆对象
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);

        //先删除口味信息
        Long id = dish.getId();
        Long[] ids = {id};
        dishFlavorMapper.delete(ids);
        //得到flavor数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //设置id属性
        if (flavors!=null && flavors.size()>0){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
            dishFlavorMapper.insert(flavors);
        }

        //删除redis中的缓存
        clearRedis("dish_*");

    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getDishById(Long id) {
        //查询菜品
        Dish dish = dishMapper.select(id);
        //查询dish_flavor表
        List<DishFlavor> dishFlavors = dishFlavorMapper.select(id);
        //创建dto对象并克隆
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 根据分类id查找菜品
     * @return
     */
    @Override
    public List<DishVO> getDishByCategoryId(Integer categoryId) {

        //使用redis做缓存
        //设置key
        String key = "dish_id"+categoryId;
        //获取redis中的数据
        List<DishVO> dishVOes = (List<DishVO>) redisTemplate.opsForValue().get(key);
        //如果redis中有对应的菜品直接返回
        if (dishVOes!=null && dishVOes.size()!=0){
            return dishVOes;
        }

        //获取菜品
        List<Dish> dishes = dishMapper.getDishesByCategoryId(categoryId);
        //创建集合存储对象
        dishVOes = new ArrayList<>();

        for (Dish dish : dishes) {
            //创建对象
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);

            //获取菜品口味
            List<DishFlavor> dishFlavor = dishFlavorMapper.select(dish.getId());

            dishVO.setFlavors(dishFlavor);
            dishVOes.add(dishVO);
        }

        //将菜品数据存储到redis中
        redisTemplate.opsForValue().set(key,dishVOes);
        return dishVOes;
    }

    //redis清理缓存
    private void clearRedis(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
